package router

import (
	"fmt"
	"github.com/fvbock/endless"
	"github.com/gin-gonic/gin"
	_ "github.com/gin-gonic/gin"
	"learn-gin/app/controller"
	"learn-gin/global"
	"strings"
	"time"
)

var (
	log = global.SUGAREDLOGGER
)

func Init() {
	fmt.Println("路由已加载")
	router := gin.New()
	router.Use(TimeMiddleware, gin.Logger(), gin.Recovery())
	/* 用户管理 */
	user := router.Group("user")
	{
		user.POST("/save", controller.User.Save)
		user.POST("/list", controller.User.List)
		user.GET("/detail", controller.User.Detail)
	}

	// 优雅的退出服务
	endless.ListenAndServe(":8080", router)
}

func CookieMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		fmt.Println("------------CookieMiddleware start------------")
		sessionId := ctx.Query("sessionId")
		fmt.Printf("ctx.Request.Host: %v\n", strings.Split(ctx.Request.Host, ":")[0])
		ctx.SetCookie("sessionId", sessionId, 0, "", strings.Split(ctx.Request.Host, ":")[0], false, true)
		fmt.Println("++++++++++++CookieMiddleware end++++++++++++")

	}
}

// 记录函数执行的时间中间件
func TimeMiddleware(ctx *gin.Context) {
	log.Info("------------TimeMiddleware 计时开始------------")
	start := time.Now()
	ctx.Next()
	Since := time.Since(start)
	log.Infof("耗时：%+v", Since)
	log.Info("++++++++++++TimeMiddleware 计时结束++++++++++++")
}
